package threadcoreknowledge.stopthreads;

/**
 * 最佳实践：catchInterruptedException 之后调用 Thread.CurrentThread().interrupt()
 * 恢复中断状态，以便后续过程中检查是否发生中断
 */
public class RightWayStopThreadInProd2 implements Runnable {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new RightWayStopThreadInProd2());
        t.start();
        Thread.sleep(1000);
        t.interrupt();
    }

    @Override
    public void run() {
        while (true) {
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("程序中断，运行结束");
                break;
            }
            System.out.println("go");
            reInterrupt();
        }
    }

    private void reInterrupt() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }
}
